using Microsoft.AspNetCore.Mvc;
using MVCDemo.Repository;
using MVCDemo.Models;
using System.Linq;
using MVCDemo.RequestParam;
namespace MVCDemo.Controllers
{
    public class ProductController : Controller
    {
        public IActionResult Index()
        {
            var Category = new EfRepository<Category>();
            var Cate = Category.Table.Where(x => x.IsDeleted == false).FirstOrDefault();
            if (Cate == null)
            {
                Category.Insert(
                    new Category
                    {
                        CategoryName = "食品"
                    }
                );
            }
            var entity = new EfRepository<Product>();
            var ent = entity.Table.Where(x => x.IsDeleted == false).ToList();
            return View(ent);
        }
        public IActionResult CreateOrEdit(int id)
        {
            var entity = new EfRepository<Product>();
            var ent = entity.Table.Where(x => x.IsDeleted == false && x.Id == id).FirstOrDefault();
            return View(ent);
        }
        public IActionResult Save(ProductParam model)
        {
            var entity = new EfRepository<Product>();
            if (model.Id > 0)
            {
                var ent = entity.Table.Where(x => x.IsDeleted == false && x.Id == model.Id).FirstOrDefault();
                ent.ProductName = model.ProductName;
                ent.Supplier = model.Supplier;
                ent.Price = model.Price;
                ent.Stock = model.Stock;
                ent.Remarks = model.Remarks;

                entity.Update(ent);
            }
            else
            {
                entity.Insert(
                    new Product
                    {
                        ProductName = model.ProductName,
                        Supplier = model.Supplier,
                        Price = model.Price,
                        Stock = model.Stock,
                        Remarks = model.Remarks,
                        CategoryId=1
                    }
                );
            }
            return Ok();
        }
        public IActionResult Delete(int id)
        {
            var entity = new EfRepository<Product>();
            entity.Delete(id);
            return RedirectToAction("Index");
        }
        public IActionResult Query(RequestQueryParam request)
        {
            var entity = new EfRepository<Product>();
            var KeyWord = request.KeyWord != null ? request.KeyWord.Trim() : "";
            var ent = entity.Table.Where(x => x.IsDeleted == false).ToList();
            if (KeyWord.Length > 0)
            {
                ent = entity.Table.Where(x => x.IsDeleted == false && x.ProductName.Contains(request.KeyWord)).ToList();
            }
            return Json(ent);
        }
    }
}